#!/bin/bash

PROJECT_PATH=${PWD}/../

if [[ "${UPDATE_SERVER_JUMP_PASSWORD_OLD}" == "" ]]; then
	# 没有权限
	echo "Permission denied"
	exit
fi

# 项目名
PROJECT_NAME="dk"

# 本地更新仓库路径
LOG_ROOT="${HOME}/dk_log"
if [ ! -d ${LOG_ROOT} ];then
	mkdir ${LOG_ROOT}
fi

# 更新服务器名
# 跳板机
JUMP_NAME="xuzhihui@45.249.245.191"
# 正式服
REMOTE_NAME="clientlog@185.19.217.21"

# 更新服命令行头
# 跳板机
JUMP_HEAD="*xuzhihui@*"
# 正式服
REMOTE_HEAD="*clientlog@*"

# 密码
# 跳板机密码
JUMP_PASSWORD=${UPDATE_SERVER_JUMP_PASSWORD}

# 初始化参数
function InitConfig()
{
	REMOTE_LOG_ROOT="/home/clientlog/clientlog"

	# 路径机路径
	JUMP_ROOT_DK="//home/xuzhihui/${PROJECT_NAME}_log"
	# 正式服路径
	REMOTE_ROOT_DK="${REMOTE_LOG_ROOT}/${PROJECT_NAME}"

	# 跳板机版本路径
	JUMP_DIR="${JUMP_ROOT_DK}"
	# 跳板机版本scp完整路径
	JUMP_FULL="${JUMP_NAME}:${JUMP_DIR}"

	# 远程版本路径_正式
	REMOTE_DIR="${REMOTE_ROOT_DK}"
	# 远程版本scp完整路径_正式
	REMOTE_FULL="${REMOTE_NAME}:${REMOTE_DIR}"

	echo "------------------------------------"
	echo "Init Config"
	echo "PROJECT_NAME     :$PROJECT_NAME"
	echo "REMOTE_LOG_ROOT  :$REMOTE_LOG_ROOT"
	echo
	echo "JUMP_DIR         :$JUMP_DIR"
	echo "JUMP_FULL        :$JUMP_FULL"
	echo
	echo "REMOTE_DIR       :$REMOTE_DIR"
	echo "REMOTE_FULL      :$REMOTE_FULL"
	echo "------------------------------------"
	echo
}

function PullLog()
{
	LOG_FILE=${LOG_DATE}.txt

#---------expect开始----------
expect << END
set timeout -1
spawn ssh -p 49226 ${JUMP_NAME}
expect "*password:"
send "${JUMP_PASSWORD}\r"
expect "${JUMP_HEAD}"
send "ssh ${REMOTE_NAME} -p 49226\r"
expect "${REMOTE_HEAD}"
send "cd ${REMOTE_LOG_ROOT}\r"
expect "${REMOTE_HEAD}"
send "sh pull_log.sh -g ${PROJECT_NAME} -d ${LOG_DATE}\r"
expect "${REMOTE_HEAD}"
send "exit\r"
expect "${JUMP_HEAD}"
set timeout -1
send "scp -r -P 49226 ${REMOTE_FULL}/${LOG_FILE} ${JUMP_ROOT_DK}/\r"
expect "${JUMP_HEAD}"
send "exit\r"
set timeout -1
spawn scp -r -P 49226 "${JUMP_FULL}/${LOG_FILE}" "${LOG_ROOT}/"
expect "*password:"
send "${JUMP_PASSWORD}\r"
expect eof
END
#---------expect结束----------
}

function FormatLog()
{
	LOG_FILE=${LOG_DATE}.txt
	LOG_FILE_FULL=${LOG_ROOT}/${LOG_FILE}

	# sed -i "" "s/\\\t/    /g" ${LOG_FILE_FULL}
	# sed -i "" 's/\\\n/\\\n&/g' ${LOG_FILE_FULL}
}

LOG_DATE=`date '+%Y%m%d'`

# 参数
# -d 20170426
while getopts :d: opt
do
	case $opt in
		d)
			# -d 20170426
			LOG_DATE="$OPTARG"
			;;
		*) echo "ERROR!!!!!-------------$opt not a option";;
	esac
done

echo "------------------------------------"
echo "Start..."

echo "------------------------------------"
echo "PROJECT_NAME    = ${PROJECT_NAME}"
echo "LOG_DATE        = ${LOG_DATE}"
echo "------------------------------------"
echo

# 初始化参数
InitConfig

PullLog
# FormatLog

echo "------------------------------------"
echo "Finished"
echo "------------------------------------"
echo